<?php

namespace app\common\service;

use app\common\CacheKey;
use app\common\model\Admin as AdminModel;
use Firebase\JWT\JWT;
use think\Cache;
use think\Config;

class Admin
{
    private $salt = "thomasyang";

    /**
     * @param $username
     * @param $password
     * @param $expire
     * @return bool|string  失败false，成功返回token
     */
    public function login($username,$password,$expire){
        $model = new AdminModel();
        $admin = $model->where(['username'=>$username,'password'=>$this->encryptPassword($password)])->find();
        if(empty($admin)) return false;
        $time = time();
        $payload = array(
            's'=>$time,
            'exp'=>$time + $expire,
            "id"=>$admin['id']
        );
        $jwtKey = Config::get("jwt_key");
        $token = JWT::encode($payload,$jwtKey);

        //清空上次登录缓存，及时更新登录信息
        Cache::clear(CacheKey::ADMIN.'#'.$admin['id']);

        return $token;
    }

    public function encryptPassword($password){
        return md5($password.$this->salt);
    }
}
